/**
 * @author   zhangyp
 * @created  2013-8-14 下午1:18:54
 * @email    zviolet@163.com
 * TODO      文件异步下载
 */
package com.bible.fire.util.file;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.FileNameMap;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import com.bible.fire.local.AppContext;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class DownloadAsynTask {
	
	private static String TAG = DownloadAsynTask.class.getSimpleName();

	/**
	 * 下载完毕之后发布广播通知调用方
	 * @param serverPath
	 * @param savePath
	 * @param pd
	 * @param broadcast
	 */
	private static void downloadFile(String serverPath, String savePath, ProgressDialog pd, String broadcast){
		
	}
	
	/**
	 * 下载多个文件完毕之后调用runnable
	 * @param serverPath
	 * @param savePath
	 * @param pd
	 * @param runnable
	 */
	public static void downloadMultiFile(String[] serverPath, String[] savePath, ProgressDialog apd, Runnable runnable){
		final ProgressDialog pd = apd;
		final Runnable fRunnable = runnable;
		final Integer fileCount = serverPath.length;
		AsyncTask<String[], Integer, Object> downloadTask = new AsyncTask<String[], Integer, Object>(){
 			
			   @Override  
		       protected void onPreExecute(){  
		           //第一个执行方法  
		           Log.d(TAG, "开始执行");
		           super.onPreExecute(); 
		           //进度条对话框
		           if( pd != null ){
		        	   pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		        	   pd.setCancelable( false );
					   pd.setMessage("正在下载第1个文件(共" + fileCount + "个)"); 
					   pd.setProgress(0);
					   pd.show();
		           }   
		       }  

				@Override
				protected Object doInBackground(String[]... path) {
					String[] serverPath = path[0];
					String[] savePath = path[1];
					for( int i = 0; i < serverPath.length; i++ ){
						downloadFileFromServer( serverPath[i], savePath[i], pd );
						publishProgress(i);
					}
					pd.dismiss();
					return null;
				}
				
				@Override
				protected void onProgressUpdate(Integer... progress) {
					pd.setMessage("正在下载第" + progress[0] + "个文件(共" + fileCount + "个)");
					pd.setProgress( 0 );
				}
				
			    @Override  
		        protected void onPostExecute(Object params) {  
		           Log.d(TAG, "下载文件完成");	                 	           
		           if( fRunnable != null ){
	        		   fRunnable.run();
	        	   }	           
		        }  
			};
			downloadTask.execute(serverPath, savePath);	
	}
	
	/**
	 * 下载单个文件完毕之后调用runnable
	 * @param serverPath
	 * @param savePath
	 * @param pd
	 * @param runnable
	 */
	public static void downloadSingleFile(String serverPath, String savePath, ProgressDialog apd, Runnable runnable){
		final ProgressDialog pd = apd;
		final Runnable fRunnable = runnable;
		AsyncTask<String, Object, File> downloadTask = new AsyncTask<String, Object, File>(){
 			
			   @Override  
		       protected void onPreExecute(){  
		           //第一个执行方法  
		           Log.d(TAG, "开始执行");
		           super.onPreExecute(); 
		           //进度条对话框
		           if( pd != null ){
		        	   pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		        	   pd.setCancelable( false );
					   pd.setMessage("正在下载文件");   
					   
					   pd.show();
		           }   
		       }  

				@Override
				protected File doInBackground(String... path) {									
					File file = downloadFileFromServer( path[0], path[1], pd );
					pd.dismiss();
					return file; 
				}
				
			    @Override  
		        protected void onPostExecute(File result) {  
		           Log.d(TAG, "下载文件完成");	                 	           
		           super.onPostExecute(result);
		           if( result != null ){
		        	   if( fRunnable != null ){
		        		   fRunnable.run();
		        	   }
		           }else{
		        	   Toast.makeText(AppContext.getContext(), "下载更新文件失败!", Toast.LENGTH_LONG).show();
		           }	           
		        }  
			};
			downloadTask.execute(serverPath, savePath);
	}
	
	private static File downloadFileFromServer(String serverPath, String savePath, ProgressDialog pd){
		try {
			URL url = new URL(serverPath);     
	        HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
	        Log.d(TAG, "content type : " + conn.getContentType() );
	        conn.setConnectTimeout(10000);     
	        //获取到文件的大小    
	        int fileLength = conn.getContentLength();
	        if( fileLength > 0 ){
	        	pd.setMax( fileLength );
	        }else{
	        	//获取不到时默认为10M
	        	pd.setMax( 10 * 1024 * 1024 );
	        }     
	        InputStream is = conn.getInputStream();     
	        File file = new File( savePath );     
	        FileOutputStream fos = new FileOutputStream(file);     
	        BufferedInputStream bis = new BufferedInputStream(is);     
	        byte[] buffer = new byte[1024];     
	        int len ;     
	        int total=0;     
	        while((len =bis.read(buffer))!=-1){     
	            fos.write(buffer, 0, len);     
	            total+= len;     
	            //获取当前下载量      
	            pd.setProgress(total);     
	        }     
	        fos.close();     
	        bis.close();     
	        is.close();     
	        return file;
		}catch(Exception e) {
			Log.e(TAG, "download apk error", e );
		}
		return null;
	}
	
	
}
